package com.example.purchase.view.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import androidx.core.content.FileProvider;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.purchase.MyApplication;
import com.example.purchase.R;
import com.example.purchase.bean.BaseBean;
import com.example.purchase.bean.PersonalBean;
import com.example.purchase.databinding.ActivityEditinfoBinding;
import com.example.purchase.network.RetrofitClient;
import com.example.purchase.network.service.HttpService;
import com.example.purchase.utils.Dialog_popWindow;
import com.example.purchase.view.base.BaseActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class EditinfoActivity extends BaseActivity<ActivityEditinfoBinding> implements View.OnClickListener {

    private Dialog dialog;
    private Uri imageUri;
    private final HttpService service = RetrofitClient.getInstance().getService(HttpService.class);
    private boolean flag = true;
    private File outputImage;
    private Intent intentPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("TAG", "onRestart: " + flag);
        if (flag){
            try {
                //将拍摄照片显示出来
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                dataBinding.header.setImageBitmap(bitmap);
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }
        }else {
            flag = true;

        }
//        service.updateHeader(outputImage,token).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .filter(new Predicate<BaseBean<List<DataBean>>>() {
//                    @Override
//                    public boolean test(BaseBean<List<DataBean>> listBaseBean) throws Throwable {
//                        Log.e("TAG", "test: " + listBaseBean.getMsg());
//                        return String.valueOf(listBaseBean.getCode()).equals("200");
//                    }
//                }).subscribe(new Consumer<BaseBean<List<DataBean>>>() {
//            @Override
//            public void accept(BaseBean<List<DataBean>> listBaseBean) throws Throwable {
//                Log.e("TAG", "accept: " + listBaseBean.getCode());
//            }
//        });
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_editinfo;
    }

    @Override
    protected void initData() {
        dataBinding.swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                            initTimeOut();
                            dataBinding.swipeRefresh.setRefreshing(false);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    @Override
    protected void initEmpty() {

    }

    @Override
    protected void initClick() {
        dataBinding.editUsername.setOnClickListener(this);
        dataBinding.editHeader.setOnClickListener(this);
    }

    @Override
    protected void initTimeOut() {
        service.getUserInfo(token).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).filter(new Predicate<BaseBean<PersonalBean>>() {
            @Override
            public boolean test(BaseBean<PersonalBean> personalBeanBaseBean) throws Throwable {
                return String.valueOf(personalBeanBaseBean.getCode()).equals("200");
            }
        }).subscribe(new Consumer<BaseBean<PersonalBean>>() {
            @Override
            public void accept(BaseBean<PersonalBean> personalBeanBaseBean) throws Throwable {
                dataBinding.name.setText(personalBeanBaseBean.getData().getUsername());
                Glide.with(getApplicationContext()).load(personalBeanBaseBean.getData().getHeadImg()).into(dataBinding.header);
            }
        });
    }

    @Override
    protected boolean isStatusBarEnabled() {
        return false;
    }

    @Override
    protected int getStatusBarColor() {
        return 0xFFFFFFFF;
    }

    @Override
    protected int getNavigationBarColor() {
        return 0xFFFFFFFF;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.edit_username:
                new Dialog_popWindow(this, R.style.dialog_pop_window, MyApplication.EDIT_MESSAGE, true,"0").show();
                break;
            case R.id.edit_header:
                //1、使用Dialog、设置style
                dialog = new Dialog(this, R.style.DialogTheme);
                //2、设置布局
                view = View.inflate(this, R.layout.dialog_layout, null);
                dialog.setContentView(view);

                Window window = dialog.getWindow();
                //设置弹出位置
                window.setGravity(Gravity.BOTTOM);
                //设置弹出动画
                window.setWindowAnimations(R.style.main_menu_animStyle);
                //设置对话框大小
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                dialog.findViewById(R.id.tv_take_photo).setOnClickListener(this);
                dialog.findViewById(R.id.tv_take_pic).setOnClickListener(this);
                dialog.findViewById(R.id.tv_cancel).setOnClickListener(this);

                dialog.show();
                break;
            case R.id.tv_take_photo:
                //创建File对象，用于存储拍照后的照片
                outputImage = new File(getExternalCacheDir(),"outPut_image.jpg");
                try {
                    if (outputImage.exists()) outputImage.delete();
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24){
                    imageUri = FileProvider.getUriForFile(this,"com.example.purchase.fileprovider",outputImage);
                }else {
                    imageUri = Uri.fromFile(outputImage);
                }
                //启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivity(intent);
                dialog.dismiss();
                break;
            case R.id.tv_take_pic:
                flag = false;
                //打开相册代码
                //创建打开相册的 Intent
                intentPic = new Intent("android.intent.action.GET_CONTENT");
                //打开页面的类型
                intentPic.setType("image/*");
                //打开相册
                startActivity(intentPic);
                dialog.dismiss();
                break;
            case R.id.tv_cancel:
                dialog.dismiss();
                break;
        }
    }
}